# 习题 10-1 文件打开的三种方式

## 1
print("1 文件.read()方式:")
with open('cp_pepa_1.txt') as file_object:
    contents = file_object.read()
    print(contents)

## 2
print("2 for line in 文件 方式:")
filename='cp_pepa_2.txt'

with open(filename) as file_object:
    for line in file_object:
        print(line)

# 3
print("3 for line in 文件,加rstrip()处理:")
filename='cp_pepa_3.txt'
with open(filename) as file_object:
    for line in file_object:
        print(line.rstrip())

## 4
print("4 文件.readlines() 方式:")
filename='cp_pepa_4.txt'

with open(filename) as file_object:
    lines = file_object.readlines()

for line in lines:
    print(line.rstrip())
print(lines)

# 10-2 replace() 字符串替换
#
msg="娘子 is real！"
print('\n'+msg)
msg=msg.replace('real','rio')
print('\n'+msg)


print("替换前")
with open('cp_pepa_5.txt') as file_object:
    contents = file_object.read()
    print(contents)

print("替换后")
with open('cp_pepa_5.txt') as file_object:
    contents = file_object.read()
    contents = contents.replace('顾依凉','他')
    print(contents)

## 对中文的替换是好使的，啊啊啊因为我打错了顾一凉。。。
## 应为replace应该是以空格为单位在分割字符串，然后对比替换

print("替换前")
with open('cp_pepa_6.txt') as file_object:
    contents = file_object.read()
    print(contents)

print("替换后")
with open('cp_pepa_6.txt') as file_object:
    contents = file_object.read()
    contents = contents.replace('Yiliang GU','He')
    print(contents)
#
# # ## 注意这个操作并没有改变文档本身
#
# # 10-3
#
filename = 'cp_pepa_7.txt'

with open(filename,'w') as file_object:
    msg=input("请输入:")
    file_object.write(msg)
# #
# # 你以为是新的大门向我敞开了吗？不，我探索见了一个全新的宇宙。我看见了一个美丽和谐欣欣向荣的正能量新世界。
#
# # 10-4 连续输入，一条占一行
#
filename = 'cp_pepa_8.txt'

with open(filename,'w') as file_object:
    while True:
        msg=input("请输入:")
        if msg != 'q':
            file_object.write(msg+'\n')
        else:
            break

# ##在这里，
# # 我对顾依凉微笑，是眼含春风。
# # 我跟顾依凉擦肩，是忍不回顾。
# # 我与顾依凉同框时低下了头，是不胜娇羞。
# # 我与顾依凉同框时转头与旁人说笑，是心仍相系。
#
# # 10-5 连续输入，一条占一行
#
# words=['在这里，',
       '顾依凉对我微笑，是欲语还休。',
       '顾依凉与我擦肩，是心中留恋。',
       '顾依凉与我同框时低下了头，是强忍喜爱。',
       '顾依凉与我同框时转头与旁人说笑，是假意避嫌。',
       ]

filename = 'cp_pepa_9.txt'

with open(filename,'w') as file_object:
    for word in words:
        file_object.write(word+'\n')
#
# 10-6 10-7 一起做了啊，想做一个计算器
#
print("Give me two numbers, and I'll add them together.")
print("Enter 'q' to quit.")

while True:
    first_number = input("\nFirst number:")

    if first_number == 'q':
        break

    second_number = input("\nSecond number:")
    if second_number == 'q':
        break

    answer = int(first_number)+int(second_number)
    print(answer)

# # 10-6 10-7 excep ValueError 加法计算器

print("Give me two numbers, and I'll add them together.")
print("Enter 'q' to quit.")

while True:
    first_number = input("\nFirst number:")

    if first_number == 'q':
        break

    second_number = input("\nSecond number:")
    if second_number == 'q':
        break

    try:
        answer = int(first_number)+int(second_number)
    except ValueError:
        print("不是数字你让我加什么加啊")
    else:
        print(answer)

# # 10-8 猫和狗 列表开文件，except 文件不存在
#
def read_txt(filenames):

    for filename in filenames:
        try:
            with open(filename) as file_object:
                contents = file_object.read()

        except FileNotFoundError:
            print('文件到底放哪了，整准了在让我找')

        else:
            print(contents)

filenames=['cp_pepa_10.txt',
           'cp_pepa_11.txt',
           'cp_pepa_102.txt']

read_txt(filenames)


# # 10-9 猫和狗 列表开文件，except pass
#
def read_txt(filenames):

    for filename in filenames:
        try:
            with open(filename) as file_object:
                contents = file_object.read()

        except FileNotFoundError:
            pass

        else:
            print(contents)

filenames=['cp_pepa_12.txt',
           'cp_pepa_13.txt',
           'cp_pepa_102.txt']

read_txt(filenames)

# # 10-10 count() 字符串中单词或短语出现了多少次
#
with open('cp_pepa_6.txt') as file_object:
    contents = file_object.read()
    print(contents)

print(contents.count('Yiliang GU'))
print(contents.count('yiliang gu'))
print(contents.lower().count('yiliang gu'))

# 10-11 10-12 json.dump 把书上的例子粘过来改

import json

def get_stored_number(filename):
    """如果存储了数字，就获取它"""
    filename = filename ### 我把这里改成函数的变量了
    try:
        with open(filename) as f_obj:
            number=json.load(f_obj)
    except FileNotFoundError:
        return None ###这里用于下面做逻辑判断
    else:
        return number


def get_new_number():
    """提示用户输入用户名"""
    ### else下面的粘过来
    number = input("What is your favorite number?")
    filename = 'number.json'
    with open(filename, 'w') as f_obj:
        json.dump(number, f_obj)
    return number


def greet_user(filename):
    """问候用户，并指出其名字"""
    number=get_stored_number(filename)
    if number:
        print("I know your favorite number! It's "+number+"!")
    else:
        username=get_new_number()
        print("We'll remember that when you come back!")

greet_user('number.json')
# greet_user('.json') 可以再试一个不存在的文件

# # 10-13 没看懂
